package com.suitsoft.bdms.commos;

import java.util.List;
import java.util.Map;
import java.util.Timer;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.suitsoft.bdms.dao.commos.CommonsDao;



/**
 * 项目初始化器.
 * 
 * <pre>
 * 加载项目用到的公共数据到ServletContext中.
 * </pre>
 * 
 * @author Suineg
 */
public class AppLoaderListener implements ServletContextListener {
	private static final long serialVersionUID = 2861248186313165619L;

	/** 日志输出对象. */
	protected Logger logger = LoggerFactory.getLogger(getClass());
	/** 计时器，用来定时执行线程. */
	Timer timer = null;
	/** 定时同步的定时器 启动类 */
	private SyncUserTimer syncUserTimer;

	/**
	 * 项目启动.
	 */
	public void contextInitialized(ServletContextEvent event) {
		logger.info("开始初始化应用程序...");
		WebApplicationContext wac = null;
		ServletContext application = event.getServletContext();
		wac = WebApplicationContextUtils.getWebApplicationContext(application);
		AppConfig conf = AppConfig.getInstance();
		CommonsDao commonsDao = (CommonsDao) wac.getBean("commonsDao");
		
		conf.setApplication(application);
		try {
			logger.info("初始化定时同步账户线程");
			List<Map<String,Object>> pointEntityList = commonsDao.getPointEntityAll(); 
			syncUserTimer = new SyncUserTimer(pointEntityList);
			syncUserTimer.init();
			logger.info("启动定同步账号线程 成功");
			
			
			application.setAttribute(Constants.SP, conf);
			logger.info("初始化应用程序成功...");
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("初始化应用程序配置失败:" + e.getMessage());
		}
	}

	/**
	 * 项目关闭.
	 */
	public void contextDestroyed(ServletContextEvent event) {
		syncUserTimer.destroy();
	}
}
